package com.cxyd.init;

import com.cxyd.client.TransportClient;
import com.cxyd.common.ShareStaticMap;
import com.cxyd.entity.PlcItemEntity;
import com.cxyd.entity.PlcSignalEntity;
import com.cxyd.entity.PlcUnitEntity;
import com.cxyd.service.PlcItemService;
import com.cxyd.service.PlcSignalService;
import com.cxyd.service.PlcUnitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class InitExecutor {
    private final ThreadPoolTaskScheduler mySchedule;
    private final PlcItemService itemService;
    private final PlcUnitService unitService;
    private final PlcSignalService signalService;

    //    各个设备的信息点
    private Map<String, List<PlcItemEntity>> itemMap = new ConcurrentHashMap<>();
    private String host = "";
    private String message = "01000000";

    public InitExecutor(ThreadPoolTaskScheduler mySchedule, PlcItemService itemService, PlcUnitService unitService, PlcSignalService signalService) {
        this.mySchedule = mySchedule;
        this.itemService = itemService;
        this.unitService = unitService;
        this.signalService = signalService;
    }

    @PostConstruct
    public void doInit() {
//        1.从[PLC_UNIT]表中获取当前需要建立连接的设备信息
        log.info("Ty_client startup! loading...");
        List<PlcUnitEntity> allUnitVo = unitService.getAllUnitVo();
//        2.通过netty与设备建立长连接
        allUnitVo.forEach(unit -> {
//            2.1.获取当前设备的所有信息点
            List<PlcItemEntity> items = itemService.selectItemByUnitNo(unit.getUnitNo());
            if (items.isEmpty()) {
                log.warn("设备[{}]未配置[PLC_ITEM]点位信息!无需连接...", unit.getUnitNo());
                return;
            }
            itemMap.put(unit.getUnitNo(), items);
            try {
                new TransportClient(unit.getIpAddr(), unit.getPort(), message).start();
            } catch (Exception e) {
                log.info("设备[{}]连接失败![{}:{}]尝试重连中...", unit.getUnitNo(), unit.getIpAddr(), unit.getPort());
            }
        });
        log.info("伺服程序启动成功!");
//        3.获取CTU小车到达或离开的信号

//        mySchedule.scheduleWithFixedDelay(() -> {
////            如果当前没有任何设备连接上不再扫描信号
//            if (ShareStaticMap.clientContext.isEmpty()) {
//                log.info("当前无可用设备!");
//                return;
//            }
////            获取可下发信号点信息
//            List<PlcSignalEntity> signals = signalService.getSignalByStatus();
//            if (signals.isEmpty()) {
//                log.info("当前无可下发信号!");
//                return;
//            }
//
//        }, 3000L);
    }
}
